package com.ruoyi.system.service.admin;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.constant.CommonConstant;
import com.ruoyi.common.core.domain.child.BannerCommonDetail;
import com.ruoyi.common.core.domain.entity.admin.AdminRichTextDB;
import com.ruoyi.common.core.domain.entity.app.AppSettingDB;
import com.ruoyi.common.exception.global.CustomException;
import com.ruoyi.common.utils.ObjectMapperUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.admin.AdminAppSettingMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AdminAppSettingService {
    @Resource
    private AdminAppSettingMapper adminAppSettingMapper;

    @Resource
    private AdminRichTextService adminRichTextService;

    public int updateAppSetting(String name, String value){
        UpdateWrapper<AppSettingDB> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set(name, value);
        return adminAppSettingMapper.update(updateWrapper);
    }

    /**
     * 根据字段名把字符串 value 反射写入对象
     *
     * @param target 目标对象
     * @param name   字段名（与实体类一致，大小写敏感）
     * @param value  字符串值
     */
    public static void setValue(Object target, String name, String value) {
        if (!StringUtils.hasText(name) || value == null) {
            return;
        }
        try {
            Field field = target.getClass().getDeclaredField(name);
            field.setAccessible(true);
            Class<?> type = field.getType();
            Object val = convert(type, value);
            field.set(target, val);
        } catch (NoSuchFieldException e) {
            throw new CustomException("字段不存在: " + name, e);
        } catch (Exception e) {
            throw new CustomException("反射赋值失败: " + name + "=" + value, e);
        }
    }

    /**
     * 字符串转常用类型
     */
    private static Object convert(Class<?> type, String value) {
        if (type == String.class) {
            return value;
        }
        if (type == int.class || type == Integer.class) {
            return Integer.parseInt(value);
        }
        if (type == long.class || type == Long.class) {
            return Long.parseLong(value);
        }
        if (type == double.class || type == Double.class) {
            return Double.parseDouble(value);
        }
        if (type == BigDecimal.class) {
            return new BigDecimal(value);
        }
        if (type == boolean.class || type == Boolean.class) {
            return Boolean.parseBoolean(value);
        }
        // 可以继续扩展
        throw new UnsupportedOperationException("未支持的类型: " + type.getName());
    }


    public AppSettingDB findSetting() {
        LambdaQueryWrapper<AppSettingDB> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(AppSettingDB::getId);
        AppSettingDB appSettingDB = adminAppSettingMapper.selectList(queryWrapper).get(0);
        // 首页广告 appSettingDB.getHomeAdJson(), BannerCommonDetail.class
        appSettingDB.setHomeAdvObj(ObjectMapperUtils.jsonToObjectList(appSettingDB.getHomeAdJson(), BannerCommonDetail.class));
        // 首页轮播图
        appSettingDB.setHomepageBannerObj(ObjectMapperUtils.jsonToObjectList(appSettingDB.getHomepageBannerJson(), BannerCommonDetail.class));
        // 金刚位
        appSettingDB.setActivityBannerObj(ObjectMapperUtils.jsonToObjectList(appSettingDB.getActivityBannerJson(), BannerCommonDetail.class));
        // 热点
        appSettingDB.setHotBannerObj(ObjectMapperUtils.jsonToObjectList(appSettingDB.getHotBannerJson(), BannerCommonDetail.class));
        return appSettingDB;
    }

    public AppSettingDB getAndHandleAppResult() {
        AppSettingDB item = this.findSetting();

        // 减少无意义的数据传输
        item.setHomeAdJson(null);
        item.setHotBannerJson(null);
        item.setActivityBannerJson(null);
        item.setHomepageBannerJson(null);

        item.setPostHome(null);
        item.setHomepageBanner(null);
        item.setActivityBanner(null);
        item.setHotBanner(null);
        item.setHomeAdv(null);

        // 处理每个list中的数据，是否可以跳转
        List<BannerCommonDetail> allList = new ArrayList<>();
        allList.addAll(item.getHomepageBannerObj());
        allList.addAll(item.getActivityBannerObj());
        allList.addAll(item.getHotBannerObj());
        allList.addAll(item.getHomeAdvObj());

        // 转为map
        Map<Long, BannerCommonDetail> map = allList.stream().collect(Collectors.toMap(BannerCommonDetail::getTargetId, Function.identity(), (k1, k2) -> k1));
        allList = allList.stream().map(entity -> map.get(entity.getTargetId())).collect(Collectors.toList());

        // 获取需要查询的id
        List<Long> needFindDetails = new ArrayList<>();
        for (BannerCommonDetail entity : allList){
            if (ObjectUtils.isEmpty(entity.getSkipUrl()) && Objects.equals(CommonConstant.PICTURE_SKIP_TYPE.POST, entity.getType()) && ObjectUtils.isNotEmpty(entity.getTargetId())){
                needFindDetails.add(entity.getTargetId());
            }
        }
        // 查询数据库
        List<AdminRichTextDB> adminRichTextDBS = adminRichTextService.selectAdminRichTextByIds(needFindDetails);
        for(AdminRichTextDB entity : adminRichTextDBS){
            // 是否可以跳转详情
            Boolean isSkip = entity.getIsSkip();
            // 不给前端显示详情id，不给跳
            if (!isSkip){
                map.get(entity.getId()).setTargetId(null);
            }
        }
        return item;
    }
}
